<script setup>
import { ref, reactive, watch } from 'vue'
import { UserRegister } from '@/api/user'
import useAppStatusStore from '@/stores/appStatus'
import { ElMessage, ElMessageBox } from 'element-plus';
const appStatusStore = useAppStatusStore()
const ruleFormRef = ref()
// 表单内容
const formData = reactive({
  nickname: '',
  phone: '',
  companyEmployee: null,
  username: '',
  isCompanyCust: null,
  isService: null,
  accountManager: '',
  invitation_code: '',
  password1: '',
  password2: '',
  showPassword1: false,
  showPassword2: false,
  submitLoading: false,
})

const checkPhone = (rule, value, callback) => {
  // console.log(rule, value, callback)
  if (rule.field !== 'phone') callback()
  if (/^1[3-9]\d{9}$/.test(value)) {
    callback()
  } else {
    callback(new Error('请输入正确的手机号!'))
  }
}
const formRules = reactive({
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { validator: checkPhone, trigger: 'blur' }
  ],
  companyEmployee: [
    { required: true, message: '请选择是否瑞达员工', trigger: 'change' }
  ],
  isCompanyCust: [
    { required: true, message: '请选择是否瑞达开户', trigger: 'change' }
  ],
  password1: [
    { required: true, message: '请设置您的帐号密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码为6到20位字符组成', trigger: 'blur' }
  ],
  password2: [
    { required: true, message: '请再次确认帐号密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码为6到20位字符组成', trigger: 'blur' }
  ]
})

// 监听部分数据(是否瑞达员工)变化，改变表单规则
watch(() => formData.companyEmployee, (newValue) => {
  if (newValue) {  // 增加姓名必填
    formRules.username = [
      { required: true, message: '请输入您的姓名', trigger: 'blur' },
    ]
  } else { // 去掉姓名必填
    if (formRules.username) {
      delete formRules.username
    }
  }
}, {immediate: true})
watch(() => formData.isCompanyCust, (newValue) => {
  if (newValue) {
    formRules.isService = [
      { required: true, message: '请选择有无客户经理', trigger: 'change' },
    ]
  } else { 
    if (formRules.isService) {
      delete formRules.isService
    }
  }
}, {immediate: true})
// 监听部分数据(有无客户经理)变化，改变表单规则
watch(() => formData.isService, (newValue) => {
  if (newValue) {  // 增加客户经理必填
    formRules.accountManager = [
      { required: true, message: '请输入客户经理', trigger: 'blur' },
    ]
  } else { 
    if (formRules.accountManager) {
      delete formRules.accountManager
    }
  }
}, {immediate: true})

const toShowLogin = () => {
  appStatusStore.showRegister = false
  appStatusStore.showLogin = true
}

const toApply = async () => {
  if (!ruleFormRef.value) return
  if (formData.password1 !== formData.password2) {
    ElMessage({
      message: '两次输入的密码不一致!',
      type: 'error'
    })
    return
  }
  await ruleFormRef.value.validate((valid) => {
    if (valid) {
      const bData = {
        nickname: formData.nickname,
        username: formData.username,
        phone: formData.phone,
        company: formData.company,
        job: formData.job,
        service: formData.accountManager,
        has_futures_account: formData.isCompanyCust,
        is_employee: formData.companyEmployee,
        invitation_code: formData.invitation_code,
        password1: formData.password1,
        password2: formData.password2,
      }
      formData.submitLoading = true
      UserRegister(bData).then((res) => {
        if (res.code === 2000) {
          appStatusStore.showRegister = false
          formData.submitLoading = false
          ElMessageBox.alert(
           '申请成功，前往登录!',
           '提示',
           {
            confirmButtonText: '前往登录',
            callback: () => {
              toShowLogin()
            }
           }
          )
        }
      }).catch(() => {
        formData.submitLoading = false
      })
    }
  })
}
</script>
<template>
  <el-dialog
    v-model="appStatusStore.showRegister"
    align-center
    class="reg-dialog"
    width="600px"
    :show-close="false"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <template #header>
      <div class="title">申请试用</div>
    </template>
    <div class="content">
      <el-form
        :model="formData"
        :rules=formRules
        :validate-on-rule-change="false"
        label-width="95" 
        ref="ruleFormRef"
        label-position="right"
      >
        <el-form-item label="邀请码">
          <el-input
            v-model="formData.invitation_code"
            class="form-input"
            placeholder="使用邀请码申请，将免费获得7天试用期"
          />
        </el-form-item>
        <el-form-item prop="nickname" label="昵称">
          <el-input
            v-model="formData.nickname"
            clearable
            placeholder="昵称"
            class="form-input"
          >
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="phone" label='手机号'>
          <el-input
            v-model="formData.phone"
            clearable
            placeholder="手机号"
            class="form-input"
          >
            <template #prefix>
              <el-icon><Phone /></el-icon>
            </template>
          </el-input>
        </el-form-item>
       <el-form-item prop="companyEmployee" label="是否瑞达员工">
         <el-select
          v-model="formData.companyEmployee"
          placeholder="是否瑞达员工"
          class="form-input"
        >
          <template #prefix>
            <el-icon><Star /></el-icon>
          </template>
          <el-option :value="true" label="是" />
          <el-option :value="false" label="否" />
         </el-select>
       </el-form-item>
        <el-form-item
          v-if="formData.companyEmployee"
          label='姓名'
          prop="username"
        >
          <el-input
            v-model="formData.username"
            clearable
            placeholder="您的姓名"
            class="form-input"
          >
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>
       <el-form-item prop="isCompanyCust" label="是否瑞达开户">
         <el-select
          v-model="formData.isCompanyCust"
          placeholder="是否瑞达开户"
          class="form-input"
        >
          <template #prefix>
            <el-icon><HotWater /></el-icon>
          </template>
          <el-option :value="true" label="是" />
          <el-option :value="false" label="否" />
         </el-select>
       </el-form-item>
        <el-form-item
          v-if="formData.isCompanyCust"
          prop="isService"
          label="有无客户经理"
        >
          <el-select
            v-model="formData.isService"
            placeholder="是否有客户经理"
            class="form-input"
          >
            <template #prefix>
              <el-icon><Aim /></el-icon>
            </template>
            <el-option :value="true" label="有" />
            <el-option :value="false" label="无" />
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="formData.isService"
          prop="accountManager" 
          label="经理姓名"
        >
          <el-input
            v-model="formData.accountManager"
            clearable
            placeholder="您的客户经理"
            class="select-input"
          >
            <template #prefix>
              <el-icon><Service /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password1" label="密码">
          <el-input
            v-model="formData.password1"
            placeholder="设置密码"
            class="form-input"
            :type="formData.showPassword1 ? 'text' : 'password'"
          >
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
            <template #suffix>
              <el-icon @click="formData.showPassword1 = !formData.showPassword1">
                <View v-if="formData.showPassword1" /> 
                <Hide v-else />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password2" label="确认密码">
          <el-input
            v-model="formData.password2"
            placeholder="再次确认密码"
            class="form-input"
            :type="formData.showPassword2 ? 'text' : 'password'"
          >
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
            <template #suffix>
              <el-icon @click="formData.showPassword2 = !formData.showPassword2">
                <View v-if="formData.showPassword2" /> 
                <Hide v-else />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="footer">
        <div class="login-account">
          <span>已有帐号?</span>
          <span class="login-text" @click="toShowLogin">马上登录</span>
        </div>
        <el-button
          type="primary"
          class="action-btn"
          :loading="formData.submitLoading"
          @click="toApply"
        >
          确认提交
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.reg-dialog {
  .title{
    text-align: center;
    color: #222;
    font-weight: 600;
    font-size: 18px;
    margin: -20px -36px -20px -20px;
    padding: 20px 30px 8px 30px;
  }
  .content {
    margin: -20px -20px -40px -20px;
    padding: 38px 30px 1px 30px;
    .form-input{
      height: 32px;
      font-size: 16px;
    }
    ::v-deep(.el-select) {
      width: 100%;
      height: 32px;
      .el-input__inner {
        height: 32px;
        font-size: 16px;
      }

      .el-input__prefix, .el-input__suffix {
        height: 32px;
        font-size: 16px;
      }

      /* 下面设置右侧按钮居中 */
      .el-input__suffix {
        top: 0px;
        display: flex;
        justify-content: center;
        align-items: center;
        flex-wrap: nowrap;
        flex-direction: row;
        align-content: flex-start;
      }
      /* 输入框加上上下边是 32px + 2px =34px */
      .el-input__icon {
        line-height: 34px;
      }
    }
    .select-input {
      height: 32px;
      font-size: 16px;
      ::v-deep(.select-trigger) {
        height: 32px;
      }
    }
  }
  .footer {
    padding: 8px 30px 20px 30px;
    margin: 0px -20px -20px -20px;
    display: flex;
    align-items: center;
    .login-account {
      font-size: 12px;
      padding-left: 85px;
      .login-text {
        color: $goldenColor;
        margin-left: 2px;
        cursor: pointer;
      }
    }
    .action-btn {
      margin-left: auto;
      height: 30px;
      width: 100px;
      font-size: 15px;
    }
  }
}
  
</style>